﻿using UnityEditor;
using System.IO;
using System.Collections.Generic;
using UnityEngine;

namespace CGF
{
    public class ChangeAssetsName
    {

        [MenuItem("CGFramework/混淆/改变所有资源文件名", priority = -900)]
        private static void ChangeAllAssetsName()
        {
            string dir = EditorUtility.OpenFolderPanel("指定目录", "Assets", "");

            if (!EditorUtility.DisplayDialog("提示", $"确定修改目录\n\n{dir}\n\n下的所有文件名吗？该操作不可逆", "确定")) return;

            List<string> filePaths = new List<string>();
            filePaths.AddRange(Directory.GetFiles(dir, "*jpg", SearchOption.AllDirectories));
            filePaths.AddRange(Directory.GetFiles(dir, "*png", SearchOption.AllDirectories));

            int total = filePaths.Count;
            for (int i = 0; i < total; i++)
            {
                if (filePaths[i].Replace("\\", "/").Contains("/Fonts/")) continue;
                if (!ChangeOneAssetName(filePaths[i])) return;
                EditorUtility.DisplayProgressBar("改变资源名", "进度: " + (i + 1) + "/" + total, (i + 1) / (float)total);
            }
            EditorUtility.ClearProgressBar();

            Debug.Log($"全部资源({total}个)改变文件名完成");
            EditorUtility.DisplayDialog("标题", $"全部资源({total}个)改变文件名完成", "确定");
        }

        private static bool ChangeOneAssetName(string path)
        {
            if (!path.Contains(Application.dataPath))
            {
                Debug.LogError("不能选择Asset外的目录");
                return false;
            }
            path = path.Replace(Application.dataPath, "Assets").Replace("\\", "/");
            string fileName = Path.GetFileNameWithoutExtension(path);
            string extension = Path.GetExtension(path);

            //每次请手动修改规则
            Debug.LogError("请手动改写以下改名规则");
            return false;

            string result = AssetDatabase.RenameAsset(path, fileName + "_gs" + extension);
            if (!string.IsNullOrEmpty(result))
            {
                Debug.LogError(result);
            }

            AssetDatabase.Refresh();
            return true;
        }
    }
}
